package net.spacebeeshooter.gui;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import net.spacebeeshooter.items.Item;
import net.spacebeeshooter.items.ItemValue;

public class ItemTable extends JTable {

	private static final long serialVersionUID = 1341046770277630842L;

	public class ColumnTypeTableModel extends DefaultTableModel {
		private static final long serialVersionUID = -5835937545544606597L;

		private Class<?>[] columnTypes;
		
		public ColumnTypeTableModel(Object[][] table, Object[] titles, Class<?>[] columnTypes) {
			super(table, titles);
			this.columnTypes = columnTypes;
		}
		
		@Override
		public Class<?> getColumnClass(int columnIndex) {
			return columnTypes[columnIndex];
		}
	}
	
	public ItemTable(Item item) {
		ItemValue[] values = item.getValues();
		int valueLength = values.length;
		String[] titles = new String[valueLength];
		Object[][] defaultValues = new Object[1][valueLength];
		Class<?>[] types = new Class<?>[valueLength];
		for (int i = 0; i != valueLength; i++) {
			ItemValue currentValue = values[i];
			Class<?> currentType = currentValue.getType();
			titles[i] = currentValue.getName() + " (" + currentType.getSimpleName() + ") ";
			types[i] = currentType;
			defaultValues[0][i] = currentValue.getDefaultValue();
		}
		setModel(new ColumnTypeTableModel(defaultValues, titles, types));	
	    JTableHeader header = getTableHeader();
	    header.setResizingAllowed(false);
		TableCellRenderer renderer = header.getDefaultRenderer();  
	    TableColumnModel columnModel = getColumnModel();  
	    for (int i = 0; i != getColumnCount(); i++) {  
		    TableColumn column = columnModel.getColumn(i);  
		    column.setHeaderRenderer(renderer);  
		    column.sizeWidthToFit();  
	    }  
	}
}
